/**
 * TradingView 网络问题修复工具
 * 解决网络超时和资源加载失败的问题
 */

/**
 * 检测网络连接状态
 */
export function checkNetworkStatus() {
  return new Promise((resolve) => {
    if (navigator.onLine === false) {
      resolve({ online: false, reason: 'offline' })
      return
    }
    
    // 尝试访问一个简单的资源来检测网络
    const testUrl = 'https://www.google.com/favicon.ico'
    const img = new Image()
    
    const timeout = setTimeout(() => {
      resolve({ online: false, reason: 'timeout' })
    }, 5000)
    
    img.onload = () => {
      clearTimeout(timeout)
      resolve({ online: true, reason: 'success' })
    }
    
    img.onerror = () => {
      clearTimeout(timeout)
      resolve({ online: false, reason: 'error' })
    }
    
    img.src = testUrl + '?t=' + Date.now()
  })
}

/**
 * 创建离线模式的TradingView配置
 */
export function createOfflineConfig() {
  return {
    library_path: './charting_library/',
    // 不设置任何可能触发网络请求的配置
    enabled_features: [
      'left_toolbar',
      'control_bar',
      'timeframes_toolbar',
      'border_around_the_chart',
      'remove_library_container_border'
    ],
    disabled_features: [
      'use_localstorage_for_settings',
      'volume_force_overlay',
      'create_volume_indicator_by_default',
      'study_templates',
      'add_to_watchlist',
      'chart_template_storage',
      'auto_save_chart_properties',
      'save_chart_properties_to_local_storage',
      'header_in_fullscreen_mode',
      'side_toolbar_in_fullscreen_mode',
      'edit_buttons_in_legend',
      'context_menus',
      'chart_property_page_style',
      'property_pages',
      'show_chart_property_page',
      'chart_crosshair_menu',
      'popup_hints',
      'study_dialog_search_control',
      'study_market_minimized',
      'constraint_dialogs_movement',
      'charting_library_debug_mode',
      'show_dom_first_time',
      'chart_last_used_symbol_on_save'
    ]
  }
}

/**
 * 显示网络错误提示
 */
export function showNetworkError(containerId) {
  const container = document.getElementById(containerId)
  if (container) {
    container.innerHTML = `
      <div style="
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        background: var(--ex-default-background-color, #f5f5f5);
        border: 1px solid var(--ex-border-color1, #ddd);
        border-radius: 4px;
        color: var(--ex-passive-font-color, #666);
        text-align: center;
        padding: 20px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      ">
        <div style="font-size: 48px; margin-bottom: 16px;">📡</div>
        <div style="font-size: 16px; margin-bottom: 8px; font-weight: 500;">网络连接问题</div>
        <div style="font-size: 14px; margin-bottom: 16px; color: var(--ex-font-color1, #999);">
          图表资源加载超时，请检查网络连接
        </div>
        <button onclick="location.reload()" style="
          background: var(--ex-font-color9, #007bff);
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
        ">刷新页面</button>
      </div>
    `
  }
}

/**
 * 创建简化的TradingView Widget配置
 */
export function createMinimalWidgetConfig(symbol, theme, containerId, datafeed, timezone) {
  return {
    symbol,
    theme,
    debug: false,
    autosize: true,
    container_id: containerId,
    datafeed,
    library_path: './charting_library/',
    locale: 'en',
    timezone,
    preset: 'mobile',
    studies: [],
    onChartReady: () => {
      console.log('✅ 离线模式图表准备就绪')
    },
    onError: (error) => {
      console.error('❌ 图表错误:', error)
      showNetworkError(containerId)
    },
    ...createOfflineConfig()
  }
}

/**
 * 网络状态监控
 */
export function startNetworkMonitoring(callback) {
  const handleOnline = () => {
    console.log('🌐 网络已连接')
    callback('online')
  }
  
  const handleOffline = () => {
    console.log('📡 网络已断开')
    callback('offline')
  }
  
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
  
  // 返回清理函数
  return () => {
    window.removeEventListener('online', handleOnline)
    window.removeEventListener('offline', handleOffline)
  }
}

// 如果在浏览器环境中，将函数挂载到window对象
if (typeof window !== 'undefined') {
  window.TradingViewNetworkFix = {
    checkNetworkStatus,
    createOfflineConfig,
    showNetworkError,
    createMinimalWidgetConfig,
    startNetworkMonitoring
  }
}
